﻿using WebApp.BLL.Base;
using WebApp.Common.Caching;
using WebApp.DAL;
using WebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using WebApp.ViewModels.Manage;
using System.Transactions;
using WebApp.ViewModels;

namespace WebApp.BLL.Manage
{
    /// <summary>
    /// 
    /// </summary>
    public class S_gridcolumnService : BaseService<S_gridcolumn>
    {
        public enum enmPagekey
        {
            工单多条件查询,
            维修月报,
            每日派工报表
        }

        #region (DAL)Repository

        #endregion

        #region 构造

        public S_gridcolumnService() : base(new S_gridcolumnRepository()) { }

        #endregion

        #region FindByKey

        public S_gridcolumn FindByKey(string pagekey, string field, int userid = 0)
        {
            return this.CurrentRepository.Entities.FirstOrDefault(p => p.Pagekey == pagekey && p.Field == field && p.Userid == userid);
        }

        #endregion

        #region GetTitle

        public string GetTitle(S_gridcolumn item, string lang)
        {
            var title = "";
            if (GlobalConst.LANG_EN.Equals(lang, StringComparison.OrdinalIgnoreCase))
            {
                title = item.Title_en;
            }
            else
            {
                title = new S_lang_resService().GetValue(item.TitleReskey, lang);
            }

            if (string.IsNullOrEmpty(title))
            {
                title = item.Title;
            }

            return title;
        }

        #endregion

        #region PageList

        public List<S_gridcolumn> PageList(int pageindex, int pagesize, string searchkey, string pagekey, int userid, string sort, string order, out int rowscount)
        {
            var T = this.CurrentRepository.Entities.Where(p => p.Userid == userid);

            //查询条件
            if (!string.IsNullOrEmpty(pagekey))
            {
                T = T.Where(p => p.Pagekey == pagekey);
            }
            if (!string.IsNullOrEmpty(searchkey))
            {
                T = T.Where(p => p.Title.Contains(searchkey) || p.Field.Contains(searchkey));
            }

            //根据属性名实现动态排序
            if (string.IsNullOrEmpty(sort))
            {
                T = T.OrderBy(p => p.Pagekey).ThenBy(p => p.Sort);
            }
            else
            {
                T = base.SortList(T, sort, order == "asc" ? true : false);
            }

            //返回记录数
            rowscount = T.Count();
            //返回分页结果
            return this.CurrentRepository.PageList(T, pageindex, pagesize).ToList();
        }

        #endregion

        #region ListByPagekey

        /// <summary>
        /// 查询用户设置的列，未设置时，查询全部
        /// </summary>
        /// <param name="pagekey"></param>
        /// <param name="userid"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public List<S_gridcolumn> ListByPagekey(string pagekey, int userid, string lang)
        {
            var fields = this.CurrentRepository.Entities
                .Where(p => p.Userid == userid && p.Pagekey == pagekey)
                .OrderBy(p => p.Sort).ThenBy(p => p.Id)
                .Select(p => p.Field)
                .ToList();

            var T = this.CurrentRepository.Entities.Where(p => p.Userid == 0 && p.Pagekey == pagekey);

            if (userid > 0 && fields.Count > 0)
            {
                T = T.Where(p => fields.Contains(p.Field));
            }

            T = T.OrderBy(p => p.Sort).ThenBy(p => p.Id);

            return T.ToList();
        }

        #endregion

        #region ListColsByPagekey

        /// <summary>
        /// 查询用户设置过的列，未设置时查询全部
        /// </summary>
        /// <param name="pagekey"></param>
        /// <param name="userid"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public List<List<EasyuiGridColumns>> ListColsByPagekey(string pagekey, int userid, string lang)
        {
            var fields = this.CurrentRepository.Entities
                .Where(p => p.Userid == userid && p.Pagekey == pagekey)
                .OrderBy(p => p.Sort).ThenBy(p => p.Id)
                .Select(p => p.Field)
                .ToList();

            var T = this.CurrentRepository.Entities.Where(p => p.Userid == 0 && p.Pagekey == pagekey);

            if (userid > 0 && fields.Count > 0)
            {
                T = T.Where(p => fields.Contains(p.Field));
            }

            T = T.OrderBy(p => p.Sort).ThenBy(p => p.Id);

            var collist = T.ToList().Select(p => new EasyuiGridColumns
            {
                field = p.Field,
                title = this.GetTitle(p, lang),
                align = p.Align,
                width = p.Width,
                sortable = p.Sortable == 1
            }).ToList();

            var result = new List<List<EasyuiGridColumns>>();
            result.Add(collist);

            return result;
        }

        #endregion

        #region ListByPagekey

        /// <summary>
        /// 查询用户自定义的列设置
        /// </summary>
        /// <param name="pagekey"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public List<S_gridcolumn> ListByPagekey(string pagekey, int userid)
        {
            return this.CurrentRepository.Entities
                .Where(p => p.Userid == userid && p.Pagekey == pagekey)
                .OrderBy(p => p.Sort).ThenBy(p => p.Id)
                .ToList();
        }

        #endregion

        #region Save

        public bool SaveList(string pagekey, int userid, List<S_gridcolumn> list)
        {
            using (var trans = new TransactionScope())
            {
                //先删除
                var oldlist = this.CurrentRepository.Entities.Where(p => p.Pagekey == pagekey && p.Userid == userid).ToList();

                foreach (var item in oldlist)
                {
                    this.CurrentRepository.Delete(item);
                }

                //保存
                int sort = 1;
                foreach (var item in list)
                {
                    var data = this.CurrentRepository.Entities.FirstOrDefault(p => p.Pagekey == pagekey && p.Field == item.Field && p.Userid == 0);

                    if (data != null)
                    {
                        var newitem = new S_gridcolumn();
                        WebApp.Common.Utils.ObjectCopyValue(data, newitem);

                        newitem.Id = 0;
                        newitem.Userid = userid;
                        //newitem.Sort = sort++;

                        this.CurrentRepository.Add(newitem);
                    }
                }

                trans.Complete();

                return true;
            }
        }

        public bool Save(S_gridcolumn model)
        {
            //更新顺序号
            var list = this.CurrentRepository.Entities.Where(p => p.Pagekey == model.Pagekey && p.Sort >= model.Sort && p.Id != model.Id).ToList();
            var sort = model.Sort + 1;
            foreach (var item in list)
            {
                item.Sort = sort++;
                this.CurrentRepository.Update(item);
            }

            if (model.Id == 0)
            {
                this.CurrentRepository.Add(model);
            }
            else
            {
                this.CurrentRepository.Update(model);
            }

            //重新更新顺序号
            list = this.CurrentRepository.Entities.Where(p => p.Pagekey == model.Pagekey).OrderBy(p => p.Sort).ToList();
            sort = 1;
            foreach (var item in list)
            {
                item.Sort = sort++;
                this.CurrentRepository.Update(item);
            }

            return true;
        }

        #endregion

        #region 删除

        public bool DeleteByUserid(string pagekey, int userid)
        {
            var list = this.CurrentRepository.Entities.Where(p => p.Pagekey == pagekey && p.Userid == userid).ToList();

            foreach (var item in list)
            {
                this.CurrentRepository.Delete(item, false);
            }

            return true;
        }

        public bool DeleteByIds(string ids)
        {
            var keys = new List<string>();

            foreach (string id in ids.Split(','))
            {
                if (string.IsNullOrEmpty(id)) continue;

                var item = this.CurrentRepository.Find(Convert.ToInt32(id));

                if (!keys.Contains(item.Pagekey))
                {
                    keys.Add(item.Pagekey);
                }

                this.CurrentRepository.Delete(item, false);
            }

            this.CurrentRepository.Save();

            //重新更新顺序号
            foreach (var pagekey in keys)
            {
                var list = this.CurrentRepository.Entities.Where(p => p.Pagekey == pagekey).OrderBy(p => p.Sort).ToList();
                var sort = 1;
                foreach (var item in list)
                {
                    item.Sort = sort++;
                    this.CurrentRepository.Update(item);
                }
            }

            return true;
        }

        #endregion

        #region Exist

        public bool Exist(int id, string pagekey, string field, int userid)
        {
            var T = this.CurrentRepository.Entities;

            if (id > 0)
            {
                var item = this.Find(id);
                var list = this.CurrentRepository.Entities.Where(p => p.Pagekey == pagekey && p.Field == field && p.Userid == userid).Select(p => p.Id).ToList();
                T = T.Where(p => !list.Contains(p.Id));
            }

            T = T.Where(p => p.Pagekey == pagekey && p.Field == field && p.Userid == userid);

            return T.Any();
        }

        #endregion

        #region DistinctPagekey

        public List<string> DistinctPagekey()
        {
            return this.CurrentRepository.Entities.Select(p => p.Pagekey).Distinct().ToList();
        }

        #endregion

        #region GetNextSort

        public int GetNextSort(string pagekey)
        {
            var list = this.CurrentRepository.Entities.Where(p => p.Pagekey == pagekey);
            if (list.Any())
                return list.Max(p => p.Sort) + 1;
            else
                return 1;
        }

        #endregion

    }
}
